import { useRef, useState, useEffect } from 'react';
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Radio,
  Button,
  Upload,
  message,
  Modal,
} from 'antd';
import { Link } from 'react-router-dom';
import Channel from 'components/Channel';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { UploadOutlined } from '@ant-design/icons';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';
import Styles from './index.module.scss';
import { addArticle, articleDetail, editArticle } from 'api/article';
import { useHistory } from 'react-router-dom';

export default function ArticlePublish(_props) {
  // 草稿和提交按钮区分
  const draftRef = useRef();
  const formRef = useRef(null);

  // 文章id
  const id = _props.match.params.id;
  console.log('id', id);
  const [imgUrl, setImgUrl] = useState('');
  const [fileList, setFileList] = useState([]);
  const [type, setType] = useState('');
  const history = useHistory();
  // console.log(history);
  //图片上传
  const props = {
    name: 'image',
    accept: '.jpg,.png,.jpeg',
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    listType: 'picture-card',
    maxCount: '3',
    onChange(info) {
      console.log('info.fileList', info.fileList);
      setFileList(info.fileList);
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success('上传成功');
      } else if (info.file.status === 'error') {
        message.error('上传失败');
      }
    },
    //图片预览
    onPreview(file) {
      console.log('file', file);
      //将图片地址存储
      setImgUrl(file.url || file.thumbUrl);
    },
    beforeUpload(file, fileList) {
      const allow = ['image/png', 'image/jpg', 'image/jpeg'];
      if (!allow.includes(file.type)) {
        message.warning('请上传jpg/png/jpeg的文件类型');
        return Upload.LIST_IGNORE;
      }
      console.log('file', file, fileList);
    },
  };
  //type改变
  const handlerType = (e) => {
    //异步的
    setType(e.target.value);
    console.log(e.target.value);
  };
  // 封装获取文章详情
  const articleDetailById = async (id) => {
    const res = await articleDetail(id);
    console.log('文章详情', res);
    console.log(formRef);
    // 传入需要回显的数据
    // 回显type的值
    const type = res.data.cover.type;
    formRef.current.setFieldsValue({ ...res.data, type });
    setType(type);
    // 图片列表设置
    setFileList(
      res.data.cover.images.map((item) => {
        return { url: item };
      })
    );
  };
  // // 获取编辑详情
  useEffect(() => {
    if (id) {
      articleDetailById(id);
    }
  }, []);

  // 提交事件
  const handlerFinish = async (value) => {
    console.log(value);
    console.log(type);
    console.log(showFileList);
    const formDate = { ...value };
    // 删除type
    delete formDate.type;
    formDate.cover = {
      type: value.type,
      images:
        value.type === 0
          ? []
          : showFileList.map((item) => item.url || item.response.data.url),
    };
    console.log(formDate);
    // 图片长度判断
    if (fileList.length < type) {
      message.warning('图片数量不对');
      return;
    }
    //发送请求
    // 如果有id编辑事件
    if (id) {
      await editArticle(id, formDate, draftRef.current);
    } else {
      await addArticle(formDate, draftRef.current);
    }
    // 提示
    message.success('操作成功');
    //跳转页面
    history.push('/list');
  };
  // 定义计算属性
  const showFileList = fileList.filter((item, index) => {
    if (type === 0) return false;
    if (type === 1) return index === 1;
    return true;
  });
  return (
    <div>
      <Card
        className={Styles.publish}
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '编辑文章' : '发布文章'}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 表单 */}
        <Form
          labelCol={{ span: 2 }}
          validateTrigger={'onChange'}
          onFinish={handlerFinish}
          initialValues={{ content: '', type: 1 }}
          ref={formRef}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入文章标题',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '请输入选择频道',
              },
            ]}
          >
            <Channel></Channel>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              { required: true, message: '请输入文章内容' },
              {
                validator: (_, value) => {
                  if (value === '<p><br></p>') {
                    return Promise.reject(new Error('请输入文章内容'));
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <ReactQuill theme="snow"></ReactQuill>
          </Form.Item>
          <Form.Item label="类型" name="type">
            <Radio.Group onChange={handlerType}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 2 }}>
            <Upload {...props} fileList={showFileList}>
              {fileList.length <= type && (
                <Button icon={<UploadOutlined />}></Button>
              )}
            </Upload>
            <Modal
              style={{ textAlign: 'center' }}
              visible={!!imgUrl}
              title="图片预览"
              onCancel={() => {
                setImgUrl('');
              }}
              onOk={() => {
                setImgUrl('');
              }}
            >
              <img src={imgUrl} style={{ width: 400 }} alt="" />
            </Modal>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 2 }}>
            <Button type="primary" htmlType="submit">
              {id ? '编辑文章' : '发布文章'}
            </Button>
            <Button
              type="primary"
              style={{ marginLeft: 20 }}
              htmlType="submit"
              onClick={() => (draftRef.current = true)}
            >
              存为草稿
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
